<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #box{
      width: 100vw;
      height: 100vh;
      overflow: scroll;
    }
    img{
      height: 300px;
      margin-bottom: 50px;
      display: block;
    }
  </style>
</head>
<body>
  <div id="box">
    <img src="" data-original="https://img0.baidu.com/it/u=2093146887,2209093944&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500" alt="">
    <img src="" data-original="https://img1.baidu.com/it/u=626755183,2526908742&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500" alt="">
    <img src="" data-original="https://img2.baidu.com/it/u=2338675418,2306268000&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" alt="">
    <img src="" data-original="https://img0.baidu.com/it/u=48465464,3484394863&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" alt="">
    <img src="" data-original="https://img0.baidu.com/it/u=2788901948,3907873318&fm=253&fmt=auto?w=500&h=281" alt="">
    <img src="" data-original="https://img1.baidu.com/it/u=3007039639,472852969&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800" alt="">
    <img src="" data-original="https://img1.baidu.com/it/u=1407687539,521000387&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=291" alt="">
    <img src="" data-original="https://img0.baidu.com/it/u=3993238299,896819757&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" alt="">
    <img src="" data-original="https://img2.baidu.com/it/u=4120653798,1128660508&fm=253&fmt=auto?w=889&h=500" alt="">
    <img src="" data-original="https://img1.baidu.com/it/u=2632231576,1274688417&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281" alt="">
  </div>


  <script>
    // 获取可视区域的高度
    const viewHeight = document.documentElement.clientHeight
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            entry.target.src = entry.target.dataset.original || ''
            entry.target.removeAttribute('data-original')
            io.unobserve(entry.target)
          }
        })
      },
      {
        threshold: 0
      }
    )
    const imgs = document.querySelectorAll('img[data-original]')
    imgs.forEach(item => {
      io.observe(item)
    })




    // function lazyLoad() {
    //   const imgs = document.querySelectorAll('img[data-original]')
    //   imgs.forEach(item => {
    //     let rect = item.getBoundingClientRect()
    //     if (rect.top < viewHeight) {
    //       item.src = item.dataset.original
    //       item.removeAttribute('data-original')
    //     }
    //   })

    // }
    // lazyLoad()
    // document.addEventListener('scroll', lazyLoad)

  </script>
</body>
</html>